import { _decorator, Component, Node, Animation } from "cc"
import { GlobalData } from "../GlobalData"
import { util } from "../util/util"
import { sp } from "cc"
import { constant } from "../framework/constant"
import { Vec3 } from "cc"
import { AudioManager } from "../framework/AudioManager"
import { Tween } from "cc"
import { Monster } from "./Monster"
import { ItemBase } from "./itemBase"
import ResManager from "../framework/ResManager"
import { instantiate } from "cc"
import { Bullet } from "./Bullet"
import { Prefab } from "cc"
import { GameItemHp } from "./GameItemHp"
import { MonsterHero } from "./MonsterHero"
import { Player } from "./Player"
import { ClientEvent } from "../framework/ClientEvent"
import { GameBossHp } from "./GameBossHp"
const { ccclass, property } = _decorator

@ccclass("MonsterBoss")
export class MonsterBoss extends MonsterHero {
  private numBeAttack: number = -1
  start(): void {
    this.playAnimation(constant.MONSTER_ANI_TYPE.WALK, true)
    this.rScale = Math.abs(this.node.scaleX)
    this.initNodeHp()
    ClientEvent.on("onGameOver", this.onGameOver, this)
  }

  init(monsterType: string) {
    super.init(monsterType)
    this.node.scaleX = Math.abs(this.node.scaleX)
  }
  protected initNodeHp() {
    const nodeHpParent = GlobalData.instance.nodeGame.getChildByName("hpParent")
    ResManager.instance.loadRes("prefabs/game/gameObject/nodeBossHp", Prefab, (err, prefab: Prefab) => {
      if (prefab) {
        this.nodeHp = instantiate(prefab)
        nodeHpParent.addChild(this.nodeHp)
        const gameHp: GameBossHp = this.nodeHp.getComponent(GameBossHp)
        gameHp.init(this.node)
      }
    })
  }

  protected onChangeHp(hp: number) {
    if (!this.maxHp) return
    this.currHp = hp
    if (this.currHp > this.maxHp) {
      this.currHp = this.maxHp
    }
    if (this.currHp <= 0) {
      this.currHp = 0
      this.isDie = true
    }
  }

  onAttackTarget(pos: Vec3) {
    AudioManager.instance.playEffect("sm_boss_attack")
    const bulletId = this.bulletId
    const strBullet: string = `prefabs/game/bullet/bullet${bulletId}`
    ResManager.instance.loadRes(strBullet, Prefab, (error, prefab) => {
      let currAttack = this.currAttack
      if (prefab) {
        if (this.nAttAckTarget && this.nAttAckTarget.isValid) {
          pos = this.nAttAckTarget.getPosition()
          let player = this.nAttAckTarget.getComponent(ItemBase)
          currAttack = player.maxHp * 0.2
        }
        let node = instantiate(prefab)
        node.scaleY = -node.scaleY
        let bullet: Bullet = node.addComponent(Bullet)
        if (bullet) {
          const selfPos = this.node.getPosition()
          const angle = util.getTwoPosXYAngle(selfPos, pos)
          node.angle = angle
          const distance = 50
          const angleInRadians = node.angle * (Math.PI / 180) // 将角度转换为弧度
          const dx = Math.cos(angleInRadians) * distance // 计算 x 方向的移动
          const dy = Math.sin(angleInRadians) * distance // 计算 y 方向的移动
          node.setPosition(this.node.positionX + dx, this.node.positionY + dy)
          bullet.initTarget(bulletId, currAttack, this.isEnemy, true)
        }
        let bulletParent: Node = GlobalData.instance.nodeGame.getChildByName("bulletParent")
        bulletParent.addChild(node)
      }
    })
  }

  private curAngle: number = 145
  private curDirect: number = 1

  createBullet() {
    AudioManager.instance.playEffect("sm_boss_attack")
    const speed: number = 8
    this.curAngle += speed * this.curDirect
    if (this.curAngle >= 235) {
      this.curDirect = -1
    } else if (this.curAngle <= 145) {
      this.curDirect = 1
    }
    const bulletId = this.bulletId
    const strBullet: string = `prefabs/game/bullet/bullet${bulletId}`
    ResManager.instance.loadRes(strBullet, Prefab, (error, prefab) => {
      let currAttack = this.currAttack
      if (prefab) {
        let node = instantiate(prefab)
        node.scaleY = -node.scaleY
        let bullet: Bullet = node.addComponent(Bullet)
        if (bullet) {
          node.angle = this.curAngle
          const distance = 50
          const angleInRadians = node.angle * (Math.PI / 180) // 将角度转换为弧度
          const dx = Math.cos(angleInRadians) * distance // 计算 x 方向的移动
          const dy = Math.sin(angleInRadians) * distance // 计算 y 方向的移动
          node.setPosition(this.node.positionX + dx, this.node.positionY + dy)
          bullet.initTarget(bulletId, currAttack, this.isEnemy, true)
        }
        let bulletParent: Node = GlobalData.instance.nodeGame.getChildByName("bulletParent")
        bulletParent.addChild(node)
      }
    })
  }

  update(deltaTime: number) {
    // return
    if (!this.node || !this.node.isValid || this.isDie) return
    if (!GlobalData.instance.getGameState() || GlobalData.instance.isBossRage) {
      this.playAnimation(constant.PLAYER_ANI_TYPE.IDLE, true)
      return
    }
    /**攻击前奏 */
    if (this.isAttackAction) {
      this.numAttackBefore += deltaTime
      if (this.numAttackBefore >= this.attackBefore) {
        this.isAttackAction = false
        this.onAttackTarget(this.posAttack)
        this.posAttack = null
      }
    }

    /**攻击cd */
    if (this.isAttackCd) {
      this.numAttackCd += deltaTime
      if (this.numAttackCd >= this.getAttackSpeed()) {
        this.isAttackCd = false
        this.endAttackTarget()
      }
      return
    }

    if (this.node.positionX > this.attackScope) {
      this.node.positionX -= this.getCurrMoveSpeed() * deltaTime
      this.playAnimation(constant.MONSTER_ANI_TYPE.WALK, true)
    } else {
      this.nAttAckTarget = this.findTargetToAttack()
      if (this.nAttAckTarget) {
        //进入攻击范围
        this.isAttackCd = true
        this.playAnimation(constant.MONSTER_ANI_TYPE.ATTACK, false)
        this.startAttAckTarget()
      }

      if (!this.isBeforeBossRage) {
        this.beforeBossRage()
      }
    }
  }
  onBeAttack(attack: number, nodeBeAttack?: Node): void {
    this.onBossRageProgress()
    super.onBeAttack(attack, nodeBeAttack)
  }

  private onBossRageProgress() {
    ClientEvent.emit("onBossBeAttack")
    if (this.numBeAttack !== -1) {
      this.numBeAttack++
      if (this.numBeAttack > 100) {
        this.unschedule(this.startBossIsRaging)
        this.startBossIsRaging()
      }
    }
  }

  private isBeforeBossRage: boolean = false
  private beforeBossRage() {
    this.numBeAttack = 0
    this.isBeforeBossRage = true
    this.scheduleOnce(this.startBossIsRaging, 6)
  }

  private startBossIsRaging() {
    if (this.numBeAttack == -1) return
    this.numBeAttack = -1
    GlobalData.instance.isBossRage = true
    ClientEvent.emit("onStartBossIsRaging")
    this.scheduleOnce(this.bossIsRaging, 3)
  }

  /**boss狂暴状态 */
  bossIsRaging() {
    ClientEvent.emit("onShark")
    this.scheduleOnce(() => {
      ClientEvent.emit("onShark")
    }, 3 + Math.random())
    this.schedule(this.createBullet, 0.06)
  }

  private onGameOver() {
    this.unscheduleAllCallbacks()
  }

  protected showDie(): void {}
}
